package com.example.zzx.dovebook.personalcenter;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.internal.DescendantOffsetUtils;
import de.hdodenhof.circleimageview.CircleImageView;

public class ImgBehavior extends CoordinatorLayout.Behavior<CircleImageView> {

    private static final String TAG = "ImgBehavior";

    private Rect mTmpRect;

    public ImgBehavior(Context context) {
        this(context, null);
    }

    public ImgBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull CircleImageView child, @NonNull View dependency) {
        return dependency instanceof AppBarLayout;
    }

    @SuppressLint("RestrictedApi")
    @Override
    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull CircleImageView child, @NonNull View dependency) {
        if (mTmpRect == null) {
            mTmpRect = new Rect();
        }
        Rect rect = mTmpRect;
        DescendantOffsetUtils.getDescendantRect(parent, dependency, rect);
        int miniHeight = ((AppBarLayout) dependency).getMinimumHeightForVisibleOverlappingContent();
        Log.e(TAG, rect.toString());
        Log.e(TAG, "miniHeight " +  miniHeight);
        if (rect.bottom <= miniHeight) {
            hide(child);
        } else {
            show(child);
        }
        return true;
    }

    private void hide(View view) {
        Animator scaleX = ObjectAnimator.ofFloat(view, view.SCALE_X, 0.0f);
        Animator scaleY = ObjectAnimator.ofFloat(view, view.SCALE_Y, 0.0f);
        Animator alpha = ObjectAnimator.ofFloat(view, View.ALPHA, 0.0F);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(scaleX, scaleY, alpha);
        set.setDuration(100L);
        set.start();
    }

    private void show(View view) {
        Animator scaleX = ObjectAnimator.ofFloat(view, view.SCALE_X, 1.0F);
        Animator scaleY = ObjectAnimator.ofFloat(view, view.SCALE_Y, 1.0F);
        Animator alpha = ObjectAnimator.ofFloat(view, view.ALPHA, 1.0F);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(scaleX, scaleY, alpha);
        set.setDuration(100L);
        set.start();
    }

}
